<template>
    <el-container style="height: 100vh;">
      <el-aside width="250px" class="aside-menu">
        <el-menu :default-active="activeSessionId" @select="handleSessionSelect">
          <el-menu-item v-for="session in sessions" :key="session.sessionId" :index="session.sessionId">
            <div class="session-item">
              <div>{{ session.fileName }}</div>
              <el-button type="text" @click.stop="deleteSession(session.sessionId)">
                <i class="el-icon-delete"></i>
              </el-button>
            </div>
          </el-menu-item>
        </el-menu>
        <el-button type="primary" @click="createNewSession">新建会话</el-button>
      </el-aside>
      <el-container>
        <el-header>
          <h1>文档关键词提取与发送</h1>
        </el-header>
        <el-main>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-card>
                <h3>提取的内容</h3>
                <el-scrollbar style="max-height: 400px;">
                  <pre class="pre-wrap">{{ formattedText }}</pre>
                </el-scrollbar>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card>
                <h3>处理后的内容</h3>
                <el-scrollbar style="max-height: 400px;">
                  <pre class="pre-wrap">{{ processedContent }}</pre>
                </el-scrollbar>
              </el-card>
            </el-col>
          </el-row>
          <el-dialog title="上传文件" :visible.sync="uploadVisible">
            <el-upload
              class="upload-demo"
              drag
              action=""
              :auto-upload="false"
              :on-change="handleFileUpload"
              accept=".pdf,.docx,.txt">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">拖拽文件到这里，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">只能上传 PDF、Word 或 TXT 文件</div>
              </el-upload>
            </el-dialog>
            <div class="floating-upload">
              <el-card>
                <div class="upload-controls">
                  <el-button type="primary" icon="el-icon-upload" @click="uploadVisible = true">上传文件</el-button>
                  <div v-if="formattedText" class="extracted-content">
                    <el-button type="primary" @click="sendToBackend">发送到后端</el-button>
                    <el-button type="primary" @click="downloadProcessedFile">下载处理后的文件</el-button>
                  </div>
                </div>
              </el-card>
            </div>
          </el-main>
        </el-container>
      </el-container>
  </template>
  
  <script>
  import axios from 'axios';
  import * as pdfjsLib from 'pdfjs-dist/build/pdf';
  import PizZip from 'pizzip';
  import Docxtemplater from 'docxtemplater';
  import { v4 as uuidv4 } from 'uuid';
  
  export default {
    data() {
      return {
        formattedText: '',
        selectedFile: null,
        sessionId: uuidv4(),
        messages: [],
        matchedKeywords: [],
        sessions: [],
        activeSessionId: null,
        uploadVisible: false,
        keywords: [],
        explanations: {},
        backendResponse: '', // 添加后端反馈的内容
        processedContent: '' // 添加处理后的内容
      };
    },
    methods: {
      async fetchVocabulary() {
        try {
          const response = await axios.get('/api/vocabulary');
          this.keywords = response.data.map(v => v.word);
          this.explanations = response.data.reduce((acc, v) => {
            acc[v.word] = v.explanation;
            return acc;
          }, {});
        } catch (error) {
          console.error('Error fetching vocabulary:', error);
        }
      },
      async handleFileUpload(file) {
        if (file) {
          this.selectedFile = file.raw;
          const fileType = file.raw.type;
          if (fileType === 'application/pdf') {
            await this.extractTextFromPDF(file.raw);
          } else if (fileType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
            await this.extractTextFromWord(file.raw);
          } else if (fileType === 'text/plain') {
            await this.extractTextFromTxt(file.raw);
          }
          this.createSession(file.raw.name);
        }
      },
      async extractTextFromPDF(file) {
        const reader = new FileReader();
        reader.onload = async (e) => {
          const typedArray = new Uint8Array(e.target.result);
          const pdf = await pdfjsLib.getDocument(typedArray).promise;
          let text = '';
          for (let pageNum = 1; pageNum <= pdf.numPages; pageNum++) {
            const page = await pdf.getPage(pageNum);
            const textContent = await page.getTextContent();
            textContent.items.forEach(item => {
              text += item.str + ' ';
            });
          }
          this.formattedText = this.extractSentencesWithKeywords(text);
        };
        reader.readAsArrayBuffer(file);
      },
      async extractTextFromWord(file) {
        const reader = new FileReader();
        reader.onload = async (e) => {
          const content = e.target.result;
          const zip = new PizZip(content);
          const doc = new Docxtemplater(zip, {
            paragraphLoop: true,
            linebreaks: true,
          });
          const text = doc.getFullText();
          this.formattedText = this.extractSentencesWithKeywords(text);
        };
        reader.readAsBinaryString(file);
      },
      async extractTextFromTxt(file) {
        const reader = new FileReader();
        reader.onload = async (e) => {
          const text = e.target.result;
          this.formattedText = this.extractSentencesWithKeywords(text);
        };
        reader.readAsText(file);
      },
      extractSentencesWithKeywords(text) {
        const sentences = text.split(/(?<=[。！？])/);
        const matchedSentences = sentences.filter(sentence => {
          const matched = this.keywords.some(keyword => sentence.includes(keyword));
          if (matched) {
            this.matchedKeywords = [...new Set([...this.matchedKeywords, ...this.keywords.filter(keyword => sentence.includes(keyword))])];
          }
          return matched;
        });
        return matchedSentences.map((sentence, index) => `${index + 1}. ${sentence}`).join(' ');
      },
      async sendToBackend() { 
        const matchedKeywordsStr = this.matchedKeywords.join(', '); 
        let contentToSend = `现在对以下词语进行定义：\n`; 
        let counter = 1; 
        this.matchedKeywords.forEach(keyword => { 
          const explanation = this.explanations[keyword]; 
          contentToSend += `${counter}.${keyword}：${explanation}\n`; 
          counter++; 
        }); 
        let highlightedText = this.formattedText; 
        this.matchedKeywords.forEach(keyword => { 
          const regex = new RegExp(`(${keyword})`, 'g'); 
          highlightedText = highlightedText.replace(regex, '“$1”'); 
        }); 
        contentToSend += `请判断下列每个句子中${matchedKeywordsStr}的意思并与上述定义比较，意思相同返回编号-1（如1-1、5-1），不同则返回编号-0： ${highlightedText}`; 
        const requestBody = { content: contentToSend, sessionId: this.activeSessionId }; 
        try { 
          const response = await axios.post('/api/content/send', requestBody); 
          const responseData = response.data; 
          if (responseData && !responseData.error) { 
            this.backendResponse = responseData.feedback; 
            this.processedContent = responseData.processed; 
          } else { 
            console.error('接收到错误或格式无效:', responseData); 
          } 
        } catch (error) { 
          console.error('发送消息错误:', error); 
          this.messages.push({ id: this.messages.length + 1, content: `发送消息错误: ${error.message}` }); 
        } 
      },
      async downloadProcessedFile() { 
        const requestBody = { content: this.processedContent }; 
        try { 
          const response = await axios.post('/api/content/download', requestBody, { responseType: 'blob' }); 
          const url = window.URL.createObjectURL(new Blob([response.data])); 
          const link = document.createElement('a'); 
          link.href = url; 
          link.setAttribute('download', 'processed.txt'); 
          document.body.appendChild(link); 
          link.click(); 
        } catch (error) { 
          console.error('下载文件错误:', error); 
          this.messages.push({ id: this.messages.length + 1, content: `下载文件错误: ${error.message}` }); 
        } 
      },
      createSession(fileName) {
        const session = {
          sessionId: uuidv4(),
          fileName: fileName,
          messages: []
        };
        this.sessions.push(session);
        this.activeSessionId = session.sessionId;
        this.saveSessions();
        this.updateMessages();
      },
      handleSessionSelect(sessionId) {
        this.activeSessionId = sessionId;
        this.updateMessages();
      },
      deleteSession(sessionId) {
        this.sessions = this.sessions.filter(s => s.sessionId !== sessionId);
        if (this.activeSessionId === sessionId) {
          this.activeSessionId = this.sessions.length > 0 ? this.sessions[0].sessionId : null;
        }
        this.saveSessions();
        this.updateMessages();
      },
      updateMessages() {
        const session = this.sessions.find(s => s.sessionId === this.activeSessionId);
        this.messages = session ? session.messages : [];
      },
      saveSessions() {
        localStorage.setItem('sessions', JSON.stringify(this.sessions));
        localStorage.setItem('activeSessionId', this.activeSessionId);
      },
      createNewSession() {
        const newSession = {
          sessionId: uuidv4(),
          fileName: `新会话-${new Date().toLocaleString()}`,
          messages: []
        };
        this.sessions.push(newSession);
        this.activeSessionId = newSession.sessionId;
        this.saveSessions();
        this.updateMessages();
      }
    },
    mounted() {
      const savedSessions = localStorage.getItem('sessions');
      if (savedSessions) {
        this.sessions = JSON.parse(savedSessions);
      }
      this.activeSessionId = localStorage.getItem('activeSessionId') || null;
      this.updateMessages();
      this.fetchVocabulary();
    }
  };
  </script>
  
  <style scoped>
  .aside-menu {
    background-color: #f5f5f5;
    padding-top: 20px;
  }
  
  .response-container {
    height: calc(100vh - 200px);
    overflow-y: auto;
    padding: 20px;
  }
  
  .floating-upload {
    position: fixed;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    width: 80%;
  }
  
  .upload-controls {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  
  .extracted-content {
    margin-top: 20px;
    width: 100%;
  }
  
  .message {
    margin: 10px 0;
  }
  
  .session-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .el-card {
    background-color: #ffffff;
    padding: 20px;
  }
  
  .pre-wrap {
    white-space: pre-wrap; /* 保留空格和换行符，并允许内容自动换行 */
    word-wrap: break-word; /* 当内容超出容器时，自动断开长单词 */
  }
  </style>
  